package com.atguigu.practices.dao.impl;

import com.atguigu.practices.bean.Employee;
import com.atguigu.practices.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class EmployeeDaoImpl implements EmployeeDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public Employee getEmployeeById(long id) {
        String sql = "select * from employee where id = ?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Employee.class), id);
    }

    @Override
    public void addEmployee(Employee employee) {
        String sql = "insert into employee (name, age, email, gender, address, salary) values (?,?,?,?,?,?)";
        int updated = jdbcTemplate.update(sql,
                employee.getName(),
                employee.getAge(),
                employee.getEmail(),
                employee.getGender(),
                employee.getAddress(),
                employee.getSalary()
        );
        System.out.println("add employee, effect rows: " + updated);
    }

    @Override
    public void updateEmployee(Employee employee) {
        String sql = "update employee set name=?,age=?,email=?,gender=?,address=?,salary=? where id=?";
        int updated = jdbcTemplate.update(sql,
                employee.getName(),
                employee.getAge(),
                employee.getEmail(),
                employee.getGender(),
                employee.getAddress(),
                employee.getSalary(),
                employee.getId()
        );
        System.out.println("update employee, effect rows: " + updated);
    }

    @Override
    public void deleteEmployee(long id) {
        String sql = "delete from employee where id = ?";
        int updated = jdbcTemplate.update(sql, id);
        System.out.println("delete employee, effect rows: " + updated);
    }

    @Override
    public List<Employee> getAllEmployees() {
        String sql = "select * from employee";

        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Employee.class));
    }
}
